#!/usr/bin/env node

var http = require("http");
var formidable = require("formidable");
var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var PORT = parseInt(process.argv[2]) || 8999;
let isFirst = true

let pathObj = {}

// let pathObj = {
//     /* 渠道 start */
//         //咪咕+ 渠道 测试+验收
//         miugPlusChannel_test_admin: '/usr/local/nginx/html_channel/channel_admin',
//         miugPlusChannel_test_partner: '/usr/local/nginx/html_channel/channel_partner',
//     /* 渠道 end */

//     /* 业务引入 start */
//         //业务引入 验收
//         businessPullIn_tst_admin: '/usr/local/nginx/html_business_tst/business_admin',
//         businessPullIn_tst_partner: '/usr/local/nginx/html_business_tst/business_partner',
//     /* 业务引入 end */

//     /* 产品中心 start */
//         //产品中心 测试
//         productCenter_test: '/usr/local/nginx/html',
//     /* 产品中心 end */

//     test: 'C:/Users/Allen/Desktop/wyl/fis3/test/receiver'
// }

var server = http.createServer(function (req, res) {
    function error(err) {
        res.writeHead(500, {
            "Content-Type": "text/plain"
        });
        res.end(err.toString()); //fail
    }

    function errorDeletFilsFail(err) {
        res.writeHead(200, {
            "Content-Type": "text/plain"
        });
        res.end('删除文件失败 \n'); //fail
    }

    function errorConfigFail(err) {
        res.writeHead(200, {
            "Content-Type": "text/plain"
        });
        res.end('路径和文件名称配置不正确 \n'); //fail
    }

    function next(from, to) {
        fs.readFile(from, function (err, content) {
            if (err) {
                error(err);
            } else {
                fs.writeFile(to, content, function (err) {
                    if (err) {
                        error(err);
                    }
                    res.writeHead(200, {
                        "Content-Type": "text/plain"
                    });
                    res.end("0"); //success
                });
            }
        });
    }

    function handlerFile(fields, files) {
        let remotePath = fields['remotePath']
        let to = fields["to"].replace(remotePath, '')
        to = pathObj[remotePath] + to;

        fs.exists(to, function (exists) {
            if (exists) {
                fs.unlink(to, function (err) {
                    next(files.file.path, to);
                });
            } else {
                fs.exists(path.dirname(to), function (exists) {
                    if (exists) {
                        next(files.file.path, to);
                    } else {
                        mkdirp(path.dirname(to), 0777, function (err) {
                            if (err) {
                                console.log('2');
                                console.log(err)
                                error(err);
                                return;
                            }
                            next(files.file.path, to);
                        });
                    }
                });
            }
        });
    }

    if (req.url == "/") {
        // show a file upload form
        res.writeHead(200, {
            "content-type": "text/html"
        });
        res.end("I'm ready for that, you know.");
    } else if (req.url == "/receiver" && req.method.toLowerCase() == "post") {
        var form = new formidable.IncomingForm();
        //删除文件夹
        form.parse(req, function (err, fields, files) {
            pathObj = require(`./configRemotePath/${fields['pathName']}.json`);

            if (isFirst) {
                var exec = require("child_process").exec;
                if(!pathObj[fields['remotePath']]){
                    console.log('--------路径和文件名称配置不正确-------失败')
                    errorConfigFail(err)
                    return
                }
                exec(
                    `rm -rf ${pathObj[fields['remotePath']]}/*`, 
                    function (err) {
                        console.log('-----开始-----')
                        if (err) {
                            console.log('--------删除文件处理错误-------失败')
                            errorDeletFilsFail(err)
                        } else {
                            console.log('--------删除文件处理错误-------成功')
                            isFirst = false
                            setTimeout(()=>{
                                isFirst = true
                            }, 1000 * 60)
                            handlerFile(fields, files)
                        }
                    }
                );
            } else {
                handlerFile(fields, files)
            }
        });
    }
})

server.listen(PORT, function () {
    console.log("receiver listening *:" + PORT);
});